from django.shortcuts import render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator

from .models import Category, Product


def shop_page(request):
    # 所有商品类别
    categories = Category.objects.all()
    # 当前商品分类
    category = request.GET.get('cate')

    # 所有商品
    products = Product.objects.filter(is_draft=False)
    if category:
        ctg = Category.objects.get(name=category)
        products = Product.objects.filter(category=ctg,is_draft=False)

    # 商品分页
    paginator_product = Paginator(products, 6)
    page = request.GET.get('page')
    paged_products = paginator_product.get_page(page)

    context = {
        'category': category,
        'categories': categories,
        'products': paged_products
    }
    return render(request, 'shop/shop.html', context)

def product_details(request, product_id):
    product_details = Product.objects.get(id=product_id)
    ctg = Category.objects.get(name=product_details.category)
    related_products = Product.objects.filter(category=ctg)
    context = {
        'product': product_details,
        'related_products': related_products
    }
    return render(request, 'shop/product-details.html', context)

def wishlist(request):
    return render(request, 'shop/wishlist.html')
